﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Win104.IEC104
{
    public class EShortFloat : InformationElement
    {
        private float value;
        public EShortFloat(float value)
        {
            this.value = value;
        }

        public EShortFloat(ByteBody data)
        {
            var num = ((data.GetByte() & 0xFF) | ((data.GetByte() & 0xFF) << 8) | ((data.GetByte() & 0xFF) << 16) | ((data.GetByte() & 0xFF) << 24));
            byte[] floatVals = BitConverter.GetBytes(num);
            value = BitConverter.ToSingle(floatVals, 0);

            //这样应该也可以
            //byte[] bfs = data.GetBytes(4);
            //value = BitConverter.ToSingle(bfs, 0);
        }

        public override int Encode(byte[] buffer, int i)
        {
            int tempVal = (int)value;
            buffer[i++] = (byte)tempVal;
            buffer[i++] = (byte)(tempVal>>8);
            buffer[i++] = (byte)(tempVal >> 16);
            buffer[i] = (byte)(tempVal >> 24);
            return 4;
        }

        public float GetValue() { return value; }

        public override string ToString()
        {
            return "短浮点数值：" + value;
        }
    }
}
